﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HtmlAgilityPack;
using Newtonsoft.Json.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;

public partial class yzadmin_data_collect_xemh : YuuzleComic.Web.UI.ManagePage
{
    protected string json = "";
    private JObject result = new JObject();
    string domain = "http://www.xemh.com";

    string baseUrl = "http://www.xemh.com/all/index.html?id={0}&p={1}&ti={2}&io={3}&key={4}&of={5}&pz={6}&s={7}";
    string id = "";
    string ti = "";
    string io = "";
    string key = "2";
    string of = "comicupdate";//排序
    int pz = 50;//每页显示
    int s = 2;//显示模式
    int p = 1;

    private string getUrl()
    {
        return string.Format(baseUrl, new object[] { id, p, ti, io, key, of, pz, s });
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            switch (Request["a"])
            {
                case "list":
                    this.ProcessList();
                    break;
                case "single":
                    this.ProcessSingle();
                    break;
                case "import":
                    this.ProcessImport();
                    break;
                default:
                    break;
            }
        }
    }

    private void ProcessImport()
    {
        try
        {
            HtmlWeb webClient = this.getWebClient();
            string[] urlArray = Request["zjurl"].Split('\n');
            Array.Reverse(urlArray);//数组倒序
            foreach (string url in urlArray)
            {
                HtmlDocument doc = webClient.Load(url);
                List<string> tpurl = new List<string>();
                HtmlNode img = doc.DocumentNode.SelectSingleNode("//img[@onload='loadNext()']");
                tpurl.Add(img.Attributes["src"].Value);
                while (img.Attributes["ondblclick"].Value.StartsWith("location.href='"))
                {
                    doc = webClient.Load(url.Substring(0, url.LastIndexOf("/") + 1) + img.Attributes["ondblclick"].Value.Split('\'')[1]);
                    img = doc.DocumentNode.SelectSingleNode("//img[@onload='loadNext()']");
                    tpurl.Add(img.Attributes["src"].Value);
                }
                YuuzleComic.Model.zj zj = new YuuzleComic.Model.zj();
                zj.cid = Convert.ToInt32(Request["id"]);
                zj.zjmc = doc.GetElementbyId("chapter_title").InnerText;
                zj.time = DateTime.Now;
                zj.isdownload = false;
                zj.tpadd = Request["tpadd"] + zj.zjmc + "/";
                zj.tps = tpurl.Count;
                zj.tpurl = string.Join("|", tpurl.ToArray());
                YuuzleComic.BLL.zj zjbll = new YuuzleComic.BLL.zj();
                if (urlArray.Length == 1 && !string.IsNullOrEmpty(Request["zjid"]))
                {
                    zj.id = int.Parse(Request["zjid"]);
                    zjbll.Update(zj);
                }
                else
                {
                    zjbll.Add(zj);
                }
            }
            result.Add("success", true);
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        finally
        {
            json = result.ToString();
        }
    }

    private void ProcessSingle()
    {
        try
        {
            HtmlWeb webClient = this.getWebClient();
            HtmlDocument doc = webClient.Load(Request["url"]);
            HtmlNode node = doc.DocumentNode.SelectSingleNode("//*[@class=\"cartoon-intro\"]");
            result.Add("mhmc",node.SelectSingleNode("img[1]").Attributes["alt"].Value);
            result.Add("mhfm", domain + node.SelectSingleNode("img[1]").Attributes["src"].Value);
            result.Add("zzmc", node.SelectSingleNode("div[1]/p[1]/a[1]").InnerText);
            result.Add("zt", node.SelectSingleNode("div[1]/p[2]/span[1]").NextSibling.InnerText);
            result.Add("classname", node.SelectSingleNode("div[1]/p[3]/a[1]") != null ? node.SelectSingleNode("div[1]/p[3]/a[1]").InnerText : "");
            result.Add("mhtc", node.SelectSingleNode("div[1]/p[4]/a") != null ? node.SelectSingleNode("div[1]/p[4]/a").InnerText : "");
            result.Add("diqu", node.SelectSingleNode("div[1]/p[5]/a") != null ? node.SelectSingleNode("div[1]/p[5]/a").InnerText : "");
            result.Add("time", node.SelectSingleNode("div[1]/p[6]/span[1]").NextSibling.InnerText);
            result.Add("mhjj", node.SelectSingleNode("div[1]/p[@class='line'][1]/span[1]").NextSibling.InnerText.Trim());
            result.Add("mhjs", node.SelectSingleNode("div[1]/p[@class='line'][2]/span[1]").NextSibling.InnerText);
            JArray chapters = new JArray();
            HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//*[starts-with(@class, 'section-list mark')]/span/a");
            if (nodes != null)
            {
                foreach (HtmlNode item in nodes)
                {
                    JObject chapter = new JObject();
                    chapter.Add("zjmc", item.InnerText);
                    chapter.Add("zjurl", domain + item.Attributes["href"].Value);
                    chapter.Add("type", item.ParentNode.ParentNode.SelectSingleNode("h6").InnerText);
                    chapters.Add(chapter);
                }
            }
            result.Add("chapters", chapters);
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        finally {
            json = result.ToString();
        }
    }

    private void ProcessList()
    {
        try
        {
            id = Request["id"];
            ti = Request["ti"];
            io = Request["io"];
            key = Request["query"];
            of = Request["of"];
            p = Convert.ToInt32(Request["page"]);
            HtmlWeb webClient = this.getWebClient();
            HtmlDocument doc = webClient.Load(this.getUrl());
            HtmlNodeCollection nodes = doc.DocumentNode.SelectSingleNode("//div[@class='sa-comic_introlist']").SelectNodes("ul/li");
            JArray data = new JArray();
            foreach (HtmlNode node in nodes)
            {
                JObject jo = new JObject();
                jo.Add("mhmc", node.SelectSingleNode("div[2]/h2/a[1]").InnerText);
                jo.Add("mhurl", domain + node.SelectSingleNode("div[2]/h2/a[1]").Attributes["href"].Value);
                jo.Add("zjmc", node.SelectSingleNode("div[2]/p[2]/span[1]").InnerText);
                jo.Add("date", node.SelectSingleNode("div[2]/p[2]/span[2]").InnerText);
                jo.Add("zt", node.SelectSingleNode("div[2]/div[@class='comic_tag_container']/a[2]").InnerText);
                jo.Add("zzmc", node.SelectSingleNode("div[2]/div[@class='comic_tag_container']/a[1]").InnerText);
                data.Add(jo);
            }
            result.Add("data", data);
            result.Add("total", 20000);
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        finally {
            json = result.ToString();
        }

    }

    private HtmlWeb getWebClient()
    {
        HtmlWeb webClient = new HtmlWeb();
        HtmlAgilityPack.HtmlWeb.PreRequestHandler handler = delegate(HttpWebRequest request)
        {
            request.Headers[HttpRequestHeader.AcceptEncoding] = "gzip, deflate";
            request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
            request.CookieContainer = new System.Net.CookieContainer();
            request.Timeout = 500000;
            return true;
        };
        webClient.PreRequest += handler;
        return webClient;
    }
}